import Common from './common'
import { apiStorage } from '../api/sys/storage'
import { apiUpload } from '../api/upload'
import JSZip from 'jszip'
import FileSaver from 'file-saver'

export const FileUtil = {
  getUrlWithRandomStr: function(url) {
    if (url.indexOf('?') > 0) {
      return url + `&ran${Common._randomString(3)}=` + Common._randomString(6)
    } else {
      return url + `?ran${Common._randomString(3)}=` + Common._randomString(6)
    }
  },
  getAliyunPoster: function(url) {
    return url + '?x-oss-process=video/snapshot,t_10000,m_fast'
  },
  updateLoadFile(file) {
    const formData = new FormData()
    formData.append('file', file)
    // console.log('updateLoadFile', formData, file)
    return apiUpload.upload(formData)
  },
  base64ToBolb: function(filename, url) {
    return new Promise(function(resolve, reject) {
      const img = new Image()
      // console.log('base64ToBolb url:', url)
      img.src = url
      img.crossOrigin = '*'
      img.onload = function() {
        const canvas = document.createElement('canvas')
        canvas.width = img.width
        canvas.height = img.height
        const ctx = canvas.getContext('2d')
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
        function blobCallback(filename) {
          return function(b) {
            try {
              const files = new window.File([b], filename, { type: b.type, size: b.size })
              resolve(files)
            } catch (e) {
              reject()
            }
          }
        }
        canvas.toBlob(blobCallback(filename), 'image/png',
          '-moz-parse-options:format=bmp;bpp=32')
      }
      img.onerror = function() {
        reject()
      }
    })
  },
  fileBatchDownload(filename, fileDataList) {
    return new Promise((resolve, reject) => {
      try {
        const data = fileDataList || [] // 需要下载打包的路径, 可以是本地相对路径, 也可以是跨域的全路径
        const zip = new JSZip()
        const promises = []
        data.forEach(item => {
          zip.file(item.filename, item.data, { binary: true }) // 逐个添加文件
        })

        Promise.all(promises).then(() => {
          zip.generateAsync({ type: 'blob' }).then(content => { // 生成二进制流
            FileSaver.saveAs(content, filename) // 利用file-saver保存文件
            resolve()
          })
        }).catch(err => {
          reject(err)
        })
      } catch (err) {
        reject(err)
      }
    })
  }
}
